import React from 'react';
import { Card, Button, Table, Space, Modal, message, TableProps } from 'antd';
import { useParams } from 'react-router-dom';
import _ from 'lodash';
import { type FormPanelObject, InputType } from 'lfun-bg-comp';
import utils from '@/utils';
import FormPanelWrapper from '../../component/FormPanelWrapper';
import { TeaQualificationsSrv } from '@/service/teacher';
import { TEACHER_CERTIFICATE_TYPE } from '@/constant/teachOptions';
import { isPermissionOperate } from '@/component/permission-button';

const TeacherQual: React.FC<{ isEditPanel?: boolean }> = ({ isEditPanel = true }) => {
  const columns: TableProps['columns'] = [
    {
      title: '教师资格种类',
      dataIndex: 'teacher_qualification_type',
      key: 'teacher_qualification_type',
      render: (text: any) => {
        text = _.isArray(text) ? text : text.split(',');
        const arr: any[] = text.map(v => utils.findLabelDeep(TEACHER_CERTIFICATE_TYPE, String(v)));
        return arr.join('-');
      },
    },
    {
      title: '教师资格证号码',
      dataIndex: 'qualification_number',
      key: 'qualification_number',
    },
    {
      title: '任教学科',
      dataIndex: 'teaching_subject',
      key: 'teaching_subject',
    },
    {
      title: '证书颁发日期',
      dataIndex: 'certificate_issue_date',
      key: 'certificate_issue_date',
    },
    {
      title: '颁发机构',
      dataIndex: 'issuing_authority',
      key: 'issuing_authority',
    },
    {
      title: '首次注册日期',
      dataIndex: 'first_registration_date',
      key: 'first_registration_date',
    },
    {
      title: '定期注册日期',
      dataIndex: 'regular_registration_date',
      key: 'regular_registration_date',
    },
    {
      title: '定期注册结论',
      dataIndex: 'regular_registration_conclusion',
      key: 'regular_registration_conclusion',
    },
    {
      title: '操作',
      key: 'actions',
      //width: 200,
      fixed: 'right',
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record) => (
        <Space>
          {isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              编辑
            </Button>
          )}
          {isEditPanel && (
            <Button type="link" onClick={() => handleDelete(record)}>
              删除
            </Button>
          )}
          {!isEditPanel && (
            <Button type="link" onClick={() => handleEdit(record)}>
              查看
            </Button>
          )}
        </Space>
      ),
    },
  ];

  const list = [
    {
      title: '',
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      span: 12,
      inputs: [
        {
          label: '教师资格证种类',
          name: 'teacher_qualification_type',
          key: 'teacher_qualification_type',
          required: true,
          inputType: InputType.select,
          renderOption: TEACHER_CERTIFICATE_TYPE,
        },
        {
          label: '教师资格证号码',
          name: 'qualification_number',
          key: 'qualification_number',
          required: true,
          textRange: [0, 20],
        },
        {
          label: '任教学科',
          name: 'teaching_subject',
          key: 'teaching_subject',
          required: true,
        },
        {
          label: '证书颁发日期',
          name: 'certificate_issue_date',
          key: 'certificate_issue_date',
          required: true,
          inputType: InputType.date,
        },
        {
          label: '颁发机构',
          name: 'issuing_authority',
          key: 'issuing_authority',
          textRange: [0, 20],
        },
        {
          label: '首次注册日期',
          name: 'first_registration_date',
          key: 'first_registration_date',
          inputType: InputType.date,
        },
        {
          label: '定期注册日期',
          name: 'regular_registration_date',
          key: 'regular_registration_date',
          inputType: InputType.date,
        },
        {
          label: '定期注册结论',
          name: 'regular_registration_conclusion',
          key: 'regular_registration_conclusion',
        },
      ],
    },
  ];

  const { id: teacher_id } = useParams();
  const [formValue, setFormValue] = React.useState({});
  const [currentRowId, setCurrentRowId] = React.useState(null);
  const [dataSource, setDataSource] = React.useState([]);

  React.useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const res = await TeaQualificationsSrv.list({ teacher_id });
    console.log('🚀 ~ fetchData ~ res:', res);
    if (res.success) {
      setDataSource(res.data);
    }
  };

  // 新增 | 编辑
  const [showFormModel, setFormModel] = React.useState(false);
  const [isEdit, setIsEdit] = React.useState(false);

  const handleAdd = () => {
    setIsEdit(false);
    setFormValue({});
    setFormModel(true);
  };

  const handleEdit = async (record: any) => {
    const { data } = await TeaQualificationsSrv.detail(record.teacher_qualifications_id);
    const params = {
      ...data,
      teacher_qualification_type: data.teacher_qualification_type ? data.teacher_qualification_type?.split(',') : [],
      // regular_registration_conclusion: data.regular_registration_conclusion
      //   ? data.regular_registration_conclusion?.split(',')
      //   : [],
      //teaching_subject: data.teaching_subject ? data.teaching_subject?.split(',') : [],
    };
    setCurrentRowId(record.teacher_qualifications_id);

    setIsEdit(true);
    setFormValue(params);
    setFormModel(true);
  };

  const handleDelete = (record: any) => {
    // content 按最字段内容为准，格式是否删除${证件类型}:${证件号码},姓名${姓名}的教师信息?
    Modal.confirm({
      title: '删除',
      content: `是否删除教师资格种类: ${record.teacher_qualification_type} 相关信息?`,
      onOk: async () => {
        console.log('OK');
        const res = await TeaQualificationsSrv.delete(record.teacher_qualifications_id);
        if (res.success) {
          message.success('删除成功');
          fetchData();
        }
      },
    });
  };

  const handleSave = async (formPanelObject: FormPanelObject) => {
    const values = formPanelObject.getFieldsValue();
    const params = {
      ...values,
      teacher_id,
    };

    params.certificate_issue_date = utils.formatTime(params.certificate_issue_date);
    params.first_registration_date = utils.formatTime(params.first_registration_date);
    params.regular_registration_date = utils.formatTime(params.regular_registration_date);
    //params.teacher_qualification_type = params.teacher_qualification_type?.join(',');
    //params.teaching_subject = params.teaching_subject?.join(',');
    //params.regular_registration_conclusion = params.regular_registration_conclusion?.join(',');

    if (isEdit) {
      params.teacher_qualifications_id = currentRowId;
    }

    // 新增 | 编辑
    const server = isEdit ? 'update' : 'add';
    const res = await TeaQualificationsSrv[server](params);
    if (res.success) {
      message.success('保存成功');
      formPanelObject.resetFields();
      setFormModel(false);
      setCurrentRowId(null);
      fetchData();
    } else {
      formPanelObject.reVaildation(res);
    }
  };

  return (
    <Card title="教师资格" bordered={false}>
      {isEditPanel && (
        <Button type="primary" style={{ marginBottom: '20px' }} onClick={handleAdd}>
          新增
        </Button>
      )}
      <Table dataSource={dataSource} columns={columns} scroll={{ x: 'max-content' }} />
      <FormPanelWrapper
        title={isEdit ? (isEditPanel ? '教师资格编辑' : '教师资格详情') : '教师资格新增'}
        visible={showFormModel}
        formValue={formValue}
        changeValue={setFormValue}
        formList={list}
        onCancel={() => setFormModel(false)}
        onSave={handleSave}
        isEdit={isEditPanel}
      />
    </Card>
  );
};

TeacherQual.defaultProps = {
  isEditPanel: true,
};

export default TeacherQual;
